import json
import sys
import socket

from PyQt5 import QtCore, QtGui, QtWidgets
from login import Login_UI
from mainUI import Ui_MainWindow
from UI_msg import msg_ui

class Chat(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(Chat, self).__init__(parent)
        #self.networkInit()

    def networkInit(self):
        #初始化一个 socket
        self.tcp_socket_client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        self.server = ('127.0.0.1', 9999)
        try:
            self.tcp_socket_client.connect(self.server)
            return self.tcp_socket_client
        except ConnectionRefusedError:
            # 如果无法链接，则弹出提示
            self.Show_Uimsg("无法链接服务器，请检查网络链接")
        # register_data = {}
        # register_data["type"] = "register"
        # register_data["account"] = "hakold"
        # register_data["password"] = "123456"
        # register_data["nickname"] = "你麻痹"
        # data = json.dumps(register_data)
        # self.tcp_socket_client.sendall(data.encode("utf-8"))
        
    def networkClose(self):
        # 断开socket链接的操作
        self.tcp_socket_client.close()

    def Show_Uimsg(self, msg):
        # 消息界面展示
        self.msgwindow = QtWidgets.QWidget() 
        self.ui2 = msg_ui()
        self.ui2.setupUi(self.msgwindow)
        self.ui2.this_msg(msg)
        self.msgwindow.show()

class LoginUi(QtWidgets.QMainWindow, Login_UI):
    def __init__(self, parent=None):
        super(LoginUi, self).__init__(parent)
        self.setupUi(self)
        self.socket_obj = Chat()
        self.socket_obj.__init__()
        self.socket_client = self.socket_obj.networkInit()
        
        

if __name__ == "__main__":
    # app = QtWidgets.QApplication(sys.argv)
    # chat = Chat()
    # chat.show()
    # sys.exit(app.exec_())
    app = QtWidgets.QApplication(sys.argv)
    login = LoginUi()
    login.show()
    sys.exit(app.exec_()) 